﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Configuration;

namespace Sinacor.OMM.HealthMonitor.Client
{
    public static class HealthMonitorClientConfigurationManager
    {

        static HealthMonitorClientConfiguration _configurationInstance;
        static String _configFile = String.Empty;
        static Int32 _tcpServerPort;

        /// <summary>
        /// Get Health Monitor Client Configuration
        /// </summary>
        public static HealthMonitorClientConfiguration HealthMonitorClientConfiguration
        {
            get
            {
                if (_configurationInstance == null)
                {

                    if (string.IsNullOrEmpty(_configFile))
                        _configFile = Path.Combine(Path.Combine(Path.GetDirectoryName(System.Configuration.ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).FilePath), "Bovespa"), "Sinacor.OMM.HealthMonitor.Client.dll");

                    System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(_configFile);

                    if (config == null)
                        throw new ConfigurationErrorsException(string.Format("Configuration file '{0}' not found.", _configFile));

                    _configurationInstance = new HealthMonitorClientConfiguration();

                    if (!Int32.TryParse(config.AppSettings.Settings["TcpServerPort"].Value, out _tcpServerPort))
                        throw new ConfigurationErrorsException("Tcp server port configuration not found.");

                    _configurationInstance.TcpServerPort = _tcpServerPort;

                    if (String.IsNullOrEmpty(config.AppSettings.Settings["TcpServerHostName"].Value))
                        throw new ConfigurationErrorsException("Tcp server host name configuration not found.");

                    _configurationInstance.TcpServerHostName = config.AppSettings.Settings["TcpServerHostName"].Value;

                    if (String.IsNullOrEmpty(config.AppSettings.Settings["HealthStatusMonitorClientLogPath"].Value))
                        throw new ConfigurationErrorsException("Tcp server host name configuration not found.");

                }

                return _configurationInstance;

            }
        }

    }
}
